package com.jeeplus.modules.api;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.api.utils.Esaipay.Http.ParameterValidator;
/**
 * 话费充值回调
 * @author Administrator
 *
 */
@CrossOrigin(origins = "*")
@Controller
@RequestMapping(value = "/api/esaipay")
public class RechargeNotify extends BaseController {
	
	@RequestMapping("/callback")
	@ResponseBody
	public String callback(HttpServletRequest request, HttpServletResponse response){
		ParameterValidator pv = new ParameterValidator(request);
		boolean result = false;
		pv.Put("partnerid");
		pv.Put("ordernumber");
		pv.Put("esupordernumber");
		pv.Put("status");
		pv.Put("custom");
		pv.Put("finishedtime");
		pv.Put("timestamp");
		pv.Put("format");
		result = pv.Validate("sign");
		
		//其它业务验证
		int errcode = 201;
		String errmsg = "缺少必要参数";
		
		try {
			if (result) {
				// 逻辑处理
				
				response.getWriter().append(GetSuccessResponse());
			} else {
				response.getWriter().append(GetFailureResponse(errcode, errmsg));
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return null;
	}
	
	/**
	 * 成功
	 * @return
	 */
	private String GetSuccessResponse() {
		return "<?xml version=\"1.0\" encoding=\"gb18030\"?><response><result>t</result><time>" + new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date())
				+ "</time></response>";
	}
	
	/**
	 * 失败
	 * @param errcode 错误编码
	 * @param errmsg 错误描述
	 * @return
	 */
	private String GetFailureResponse(int errcode, String errmsg) {
		return "<?xml version=\"1.0\" encoding=\"gb18030\"?><response><result>f</result><time>" + new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date())
				+ "</time><errcode>" + errcode + "</errcode><errmsg>"+ errmsg + "</errmsg></response>";
	}
}
